package com.example.rbacmanage.controller;

import com.example.rbacmanage.annotation.LogAnnotation;
import com.example.rbacmanage.common.Constant;
import com.example.rbacmanage.common.Result;
import com.example.rbacmanage.entity.SysJob;
import com.example.rbacmanage.exception.TaskException;
import com.example.rbacmanage.service.SysJobService;
import com.example.rbacmanage.util.CronUtils;
import com.example.rbacmanage.util.ScheduleUtils;
import org.apache.commons.lang3.StringUtils;
import org.quartz.SchedulerException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import java.util.List;

import static com.example.rbacmanage.common.Result.error;
import static com.example.rbacmanage.common.Result.success;

/**
 * 调度任务信息操作处理
 * 
 * @author ruoyi
 */
@RestController
@RequestMapping("/monitor/job")
public class SysJobController
{
    @Autowired
    private SysJobService sysJobService;

    /**
     * 查询定时任务列表
     */
    @PreAuthorize("hasAnyAuthority('monitor:job:page')")
    @GetMapping(value = "/page")
    public Result page(SysJob sysJob)
    {
        return Result.success(sysJobService.getPage(sysJob));
    }

    /**
     * 导出定时任务列表
     */
    @PreAuthorize("hasAnyAuthority('monitor:job:export')")
    @LogAnnotation(module = "定时任务", operation = "导出")
    @PostMapping("/export")
    public void export(HttpServletResponse response, SysJob sysJob)
    {
        List<SysJob> list = sysJobService.getAll(sysJob);
        /*ExcelUtil<SysJob> util = new ExcelUtil<SysJob>(SysJob.class);
        util.exportExcel(response, list, "定时任务");*/
    }

    /**
     * 获取定时任务详细信息
     */
    @PreAuthorize("hasAnyAuthority('monitor:job:query')")
    @GetMapping(value = "/{jobId}")
    public Result getInfo(@PathVariable("jobId") Long jobId)
    {
        return Result.success(sysJobService.getById(jobId));
    }

    /**
     * 新增定时任务
     */
    @PreAuthorize("hasAnyAuthority('monitor:job:add')")
    @LogAnnotation(module = "定时任务", operation = "新增定时任务")
    @PostMapping
    public Result add(@RequestBody SysJob job) throws SchedulerException, TaskException
    {
        if (!CronUtils.isValid(job.getCronExpression()))
        {
            return Result.error("新增任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        }
        else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constant.LOOKUP_RMI))
        {
            return Result.error("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constant.LOOKUP_LDAP, Constant.LOOKUP_LDAPS }))
        {
            return Result.error("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constant.HTTP, Constant.HTTPS }))
        {
            return Result.error("新增任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constant.JOB_ERROR_STR))
        {
            return Result.error("新增任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        }
        else if (!ScheduleUtils.whiteList(job.getInvokeTarget()))
        {
            return Result.error("新增任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        job.setCreateBy(null);
        sysJobService.insertJob(job);
        return Result.success();
    }

    /**
     * 修改定时任务
     */
    @PreAuthorize("hasAnyAuthority('monitor:job:edit')")
    @LogAnnotation(module = "定时任务", operation = "修改定时任务")
    @PutMapping
    public Result edit(@RequestBody SysJob job) throws SchedulerException, TaskException {
        if (!CronUtils.isValid(job.getCronExpression()))
        {
            return Result.error("修改任务'" + job.getJobName() + "'失败，Cron表达式不正确");
        }
        else if (StringUtils.containsIgnoreCase(job.getInvokeTarget(), Constant.LOOKUP_RMI))
        {
            return Result.error("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'rmi'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constant.LOOKUP_LDAP, Constant.LOOKUP_LDAPS }))
        {
            return Result.error("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'ldap(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), new String[] { Constant.HTTP, Constant.HTTPS }))
        {
            return Result.error("修改任务'" + job.getJobName() + "'失败，目标字符串不允许'http(s)'调用");
        }
        else if (StringUtils.containsAnyIgnoreCase(job.getInvokeTarget(), Constant.JOB_ERROR_STR))
        {
            return Result.error("修改任务'" + job.getJobName() + "'失败，目标字符串存在违规");
        }
        else if (!ScheduleUtils.whiteList(job.getInvokeTarget()))
        {
            return Result.error("修改任务'" + job.getJobName() + "'失败，目标字符串不在白名单内");
        }
        sysJobService.updateJob(job);
        return Result.success();
    }

    /**
     * 定时任务状态修改
     */
    @PreAuthorize("hasAnyAuthority('monitor:job:changeStatus')")
    @LogAnnotation(module = "定时任务", operation = "定时任务状态修改")
    @PutMapping("/changeStatus")
    public Result changeStatus(@RequestBody SysJob job) throws SchedulerException
    {
        SysJob newJob = sysJobService.getById(job.getJobId());
        newJob.setStatus(job.getStatus());
        sysJobService.changeStatus(newJob);
        return Result.success();
    }

    /**
     * 定时任务立即执行一次
     */
    @PreAuthorize("hasAnyAuthority('monitor:job:changeStatus')")
    @LogAnnotation(module = "定时任务", operation = "定时任务立即执行一次")
    @PutMapping("/run")
    public Result run(@RequestBody SysJob job) throws SchedulerException
    {
        boolean result = sysJobService.run(job);
        return result ? Result.success() : Result.error("任务不存在或已过期！");
    }

    /**
     * 删除定时任务
     */
    @PreAuthorize("hasAnyAuthority('monitor:job:remove')")
    @LogAnnotation(module = "定时任务", operation = "删除定时任务")
    @DeleteMapping("/{jobIds}")
    public Result remove(@PathVariable(value = "jobIds") Long[] jobIds) throws SchedulerException
    {
        sysJobService.removeJob(jobIds);
        return Result.success();
    }
}
